<template>
  <div>
    <div>
      <input type="text" v-model="name" placeholder="搜索" />
    </div>

    <div style="margin-top: 20px;">
      <table border width="600" cellpadding="0" cellspacing="0" align="center">
        <thead>
          <tr>
            <th>物品名称</th>
            <th>物品单价</th>
            <th>物品数量</th>
            <th>物品总价</th>
            <th>操作</th>
          </tr>
        </thead>
        
        <tbody>
          <tr v-for="(item, index) in data" :key="index">
            <td>{{ item.name }}</td>
            <td>{{ item.price }}</td>
            <td>
              <button @click="item.num > 1 ? (item.num--, total()) : null">-</button>
              {{ item.num }}
              <button @click="item.num < 99 ? (item.num++, total()) : null">+</button>
            </td>
            <td>{{ item.price * item.num }}</td>
            <td>
              <button @click="del(index)">删除</button>
            </td>
          </tr>
        </tbody>

        <tfoot>
          <tr>
            <td colspan="4">总计：{{ $total }}</td>
          </tr>
        </tfoot>
      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
  import {ref, reactive} from 'vue'
  
  interface Data {
    name: string,
    price: number,
    num: number,
  }

  let name = ref("")
  let $total = ref<number>(0)
  let data = reactive<Data[]>([
    {name: '苹果', price: 4, num: 8},
    {name: '香蕉', price: 3.5, num: 10},
    {name: '柠檬', price: 5, num: 2},
  ])

  const total = () => {
    $total.value = data.reduce((pre: number, cur: Data) => {
      return pre + cur.price * cur.num
    }, 0)
  }
  
  total()

  const del = (index: number) => {
    data.splice(index, 1)
    total()
  }
</script>

<style scoped>

</style>